<?php

namespace App\Models\V6;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;


class ReadPartyModel extends Model
{

    protected $table = 'read_party_member';

    /*
     * 获取用户的读书会
     * @param userId 读书会成员ID
     * */
    public function get_member_read_party($userId)
    {


        $colum = [
            'b.ReaParID',
            'b.MemNumber',
            'b.ReaParType',
            'b.States',
            'b.ReaParName',
            'b.FilePath1',
            'b.Description',
            'b.Regulation',
            'b.AddDate',
            'a.is_employee'
        ];

        $readPartys = DB::table("read_party_member AS a")
            ->leftJoin("read_party AS b", "b.ReaParID", "=", "a.read_party_id")
            ->where('a.user_id', $userId)
            ->where('a.is_delete', 0)
            ->where('b.DeleteMark', 1)
            ->select($colum)
            ->get();


        $arr = [];
        foreach ($readPartys as $k => $par) {
            if ($par->ReaParType == 1 && $par->is_employee == 0) {
                continue;
            }
            $img            = $par->FilePath1 ? $par->FilePath1 : "/images/default-images/default-read-party-img.jpg";
            $img            = env('ADMIN_HOST') . $img;
            $par->FilePath1 = $img;
            array_push($arr, $par);
        }
        return $arr;
    }

    public function get_member_read_party_and_notice($userId)
    {
        $colum = [
            'b.ReaParID',
            'b.MemNumber',
            'b.ReaParType',
            'b.States',
            'b.ReaParName',
            'b.FilePath1',
            'b.Description',
            'b.Regulation',
            'b.AddDate',
            'a.is_employee'
        ];

        $readPartys = DB::table("read_party_member AS a")
            ->leftJoin("read_party AS b", "b.ReaParID", "=", "a.read_party_id")
            ->where('a.user_id', $userId)
            ->where('a.is_delete', 0)
            ->where('b.DeleteMark', 1)
            ->select($colum)
            ->groupBy('a.read_party_id','a.user_id')
            ->get();

        $arr        = [];
        foreach ($readPartys as $k => $par) {
            if ($par->ReaParType == 1 && $par->is_employee == 0) {
                continue;
            }
            $img            = $par->FilePath1 ? $par->FilePath1 : "/images/default-images/default-read-party-img.jpg";
            $img            = env('ADMIN_HOST') . $img;
            $par->FilePath1 = $img;
            array_push($arr, $par);
        }
        return $arr;
    }


    /**
     * 获取读书会信息
     * */
    public function get_read_party_info($readPartyId)
    {
        $readPartyInfo = DB::table('read_party')->where('ReaParID', $readPartyId)->first();

        if ($readPartyInfo)
        {
            if (!$readPartyInfo->FilePath1)
            {
                $readPartyInfo->FilePath1 = "/images/default-images/default-read-party-img.jpg";
            }

            if (!$readPartyInfo->FilePath2)
            {
                $readPartyInfo->FilePath2 = "/images/default-images/default-read-party-img.jpg";
            }

            $readPartyInfo->FilePath1 = env('ADMIN_HOST') . $readPartyInfo->FilePath1;
            $readPartyInfo->FilePath2 = env('ADMIN_HOST') . $readPartyInfo->FilePath2;
        }
        if(is_null($readPartyInfo->Regulation))
        {
            $readPartyInfo->Regulation = "";
        }
        return $readPartyInfo;
    }


    /**
     * 创建读书会
     * @param readPartyInfo 读书会数据
     * */
    public function add_read_party($readPartyData)
    {
        $dateTime                     = date_time();
        $readPartyData['ReleaseDate'] = $dateTime;
        $readPartyData['AddDate']     = $dateTime;

        $readId = DB::table('read_party')->insertGetId($readPartyData);
        return $readId;
    }

    /**
     * 更新读书会信息
     * @param integer readPartyId 读书会ID
     * @param array readpartyInfo 读书会信息
     * @return boolean
     * */
    public function update_read_party($readPartyId, array $readPartyInfo)
    {
        if ($readPartyId > 0) {
            $readPartyInfo['ReleaseDate'] = date_time();
            DB::table('read_party')->where('ReaParID', $readPartyId)->update($readPartyInfo);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 添加读书会会员
     * @param $readPartyId  int     读书会ID
     * @param $userId       int     用户ID
     * @param $departmentId int     部门ID
     * @param $otherInfo    Array   其他信息
     * @return Object
     * */
    public function add_read_party_member($readPartyId, $userId,$departmentId = 0, array $otherInfo = [])
    {
        $date        = date_time();
        $data        = [
            'read_party_id' => $readPartyId,
            'user_id'       => $userId,
            'department_id' => $departmentId,
            'add_date'      => $date,
            'release_date'  => $date,
        ];
        $data       = array_merge($data,$otherInfo);
        $result      = DB::table('read_party_member')->insert($data);
        return $result;
    }

    /**
     * 修改读书会会员信息
     * @param integer readpartyId 读书会ID
     * @param integer userId 用户ID
     * @param array $info 修改的信息
     * */
    public function update_read_party_member($readPartyId, $userId, $info)
    {
        $result = DB::table('read_party_member')
            ->where('read_party_id', $readPartyId)
            ->where('user_id', $userId)
            ->update($info);
        return $result;
    }

    /**
     * 移除读书会成员
     * @param integer readPartyId 读书会ID
     * @param integer userId      用户ID
     * @return boolean
     * */
    public function remove_party_member($readPartyId, $userId)
    {
        $result = DB::table('read_party_member')
            ->where('read_party_id', $readPartyId)
            ->where('user_id', $userId)
            ->update(['is_delete' => 1]);
        return $result;
    }

    /**
     * 获得读书会的所有成员
     * @param integer readPartyId 读书会ID
     * @param string keywords 关键字查询
     * @param integer limit 数量限制
     * @param integer $page 页数
     * */
    public function get_read_party_member($readPartyId, $keywords = '', $limit = 0, $page = 1)
    {
        $perPage = 10;
        $begin   = ($page - 1) * $perPage;
        $SQL     = "SELECT
                      a.MemNumber,
                      a.UserName,
                      a.UserID,
                      a.FilePath1,
                      a.YourName,
                      d.StudyMoney,
                      m.read_user_id,
                      m.reward_right,
                      m.is_employee,
                      m.add_date,
                      m.is_delete,
                      GROUP_CONCAT(t.department_name) AS department_name,
                      t.department_id
                FROM  read_party_member AS m
           LEFT JOIN  memberinfo        AS a    ON a.UserID = m.user_id
           LEFT JOIN  company_department AS t   ON t.department_id = m.department_id
           LEFT JOIN ( SELECT StudyMoney,MemNumber FROM membermoney b WHERE b.ReaParID = $readPartyId  ) AS d
                  ON  d.MemNumber = a.MemNumber
                WHERE m.read_party_id = $readPartyId
                AND   m.is_delete = 0
                AND   a.DeleteMark = 1 ";

        if($keywords)
        {
            $SQL .= " AND (a.YourName like '%{$keywords}%' or a.UserName like '%{$keywords}%')";
        }
        $SQL .= " AND a.States = 1 GROUP BY m.read_party_id,m.user_id ORDER BY a.ReleaseDate DESC ";
        if ($limit > 0)
        {
            $SQL .= " LIMIT $limit";
        }
        else
        {
            $SQL .= " LIMIT $perPage OFFSET $begin";
        }

        $members = DB::select($SQL);
        foreach ($members as $mem) {
            $mem->FilePath1  = change_member_head_img($mem->FilePath1);
            $mem->StudyMoney = $mem->StudyMoney ? $mem->StudyMoney : 0;
        }
        return $members;
    }

    /**
     * 读书会某个会员的详细信息
     * @param integer userId 用户ID
     * @param integer readPartyId 读书会ID
     *
     * */
    public function get_read_party_member_detail($userId, $readPartyId)
    {
        $readPartyInfo  = $this->get_read_party_info($readPartyId);
        $comId          = $readPartyInfo->company_id;
        if ($comId > 0) {
            $info = db::table('memberinfo as a')
                ->leftJoin('read_party_member as b', 'b.user_id', '=', 'a.UserID')
		        ->leftJoin('read_party as k', 'k.ReaParID', '=', 'b.read_party_id')
                ->leftjoin('company_user as h','h.user_id','=',DB::raw('a.UserID and h.company_id ='.$comId))
                ->leftjoin('company_department as d','d.department_id','=','b.department_id')
                ->where('a.UserID', $userId)
                ->where('b.read_party_id', $readPartyId)
                ->where('b.is_delete', 0)
                ->where('h.is_delete', 0)
                ->select('a.*','b.add_date','b.reward_right','b.look_gift_right','b.is_employee','h.job','d.department_id','d.department_name')
                ->first();
        } else {
            $info            = db::table('memberinfo as a')
                ->leftJoin('read_party_member as b', 'b.user_id', '=', 'a.UserID')
                ->leftJoin('read_party as k', 'k.ReaParID', '=', 'b.read_party_id')
                ->where('a.UserID', $userId)
                ->where('b.read_party_id', $readPartyId)
                ->select('a.*','b.add_date', 'b.reward_right', 'b.is_employee')
                ->first();

            $info->is_delete        = 0;
            $info->look_gift_right  = 0;
        }
        return $info;
    }

    /**
     * 获取读书会部门会员
     * @param integer readpartyId 读书会ID
     * @param integer departmentId  部门ID
     * @param string keywords 关键字
     *
     * */
    public function get_read_party_department_member($readPartyId, $departmentId,$keywords="")
    {
        $SQL     = "SELECT
                      a.MemNumber,
                      a.UserID,
                      a.FilePath1,
                      a.YourName,
                      d.StudyMoney,
                      m.reward_right,
                      m.is_employee,
                      m.is_delete,
                      h.is_delete as h_is_delete,
                      t.department_name,
                      t.department_id
                FROM  read_party_member   AS m
          LEFT JOIN   read_party          AS r ON  r.ReaParID     = m.read_party_id
           LEFT JOIN  memberinfo          AS a ON a.UserID        = m.user_id
           LEFT JOIN  company_user        AS h ON h.user_id       = m.user_id AND  h.department_id = m.department_id
           LEFT JOIN  company_department  AS t ON t.department_id = m.department_id
           LEFT JOIN ( SELECT StudyMoney,MemNumber FROM membermoney b WHERE b.ReaParID = $readPartyId  ) AS d
                  ON  d.MemNumber = a.MemNumber
                WHERE m.read_party_id = $readPartyId
                AND   m.is_delete     = 0
                AND   h.department_id = $departmentId
                AND   h.is_delete=0
                AND   a.States = 1 ORDER BY a.ReleaseDate DESC";
        $members = DB::select($SQL);
        foreach ($members as $mem) {
            $mem->FilePath1  = change_member_head_img($mem->FilePath1);
            $mem->StudyMoney = $mem->StudyMoney ? $mem->StudyMoney : 0;
        }
        return $members;
    }

    /**
     * 获取读书会的成员数量
     * @param integer readPartyId 读书会ID
     * @return integer
     * */
    public function count_read_party_number($readPartyId,$keywords = '')
    {
        $total = DB::table('read_party_member as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->select(DB::raw('count(distinct(a.user_id)) as total'))
            ->where('a.read_party_id', $readPartyId)
            ->where('a.is_delete', 0)
            ->where('b.DeleteMark',1);
        if($keywords){
            $total = $total->where(function($query) use ($keywords){
                $keywords = "%{$keywords}%";
                $query->orWhere('b.YourName',"like",$keywords)
                    ->orWhere('b.UserName',"like",$keywords)
                    ->orWhere('b.NickName',"like",$keywords);
            });
        }
        $total = $total->first();
        return $total->total;
    }

    /**
     * 检查读书会是否已有了某个会员
     * @param integer readPartyId 读书会ID
     * @param integer userId 会员ID
     * @return boolean
     * */
    public function check_read_party_member_exists($readPartyId, $userId)
    {

        $count = DB::table('read_party_member')
            ->where('read_party_id', $readPartyId)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        return $count ? true : false;
    }

    /**
     * 检查读书会名称是否可用
     * @param string readPartyName 读书会名称
     * @return boolean
     * */
    public function check_read_party_name_exists($readPartyName)
    {
        $name = DB::table('read_party')->where('ReaParName', $readPartyName)->where('DeleteMark', 1)->first();
        if ($name) {
            return true;
        } else {
            return false;
        }
    }


    /*
     * 获得公司的读书会
     * @param companyId 公司ID
     * */
    public function get_company_read_party($companyId)
    {
        $readPartys = DB::table('read_party')->where('DeleteMark', 1)->where('company_id', $companyId)->get();
        $readPartys = $readPartys ? $readPartys : [];
        return $readPartys;
    }


    /**
     * 获得读书会的广告
     *
     * */
    public function get_read_party_ad()
    {
        //广告
        $bookHots = DB::table('bookhots')->select('LinkUrl', 'FilePath1', 'BoHoTitle', 'SortNumber')
            ->where('BoHoType', '2')
            ->where('IsShow', '1')
            ->where('DeleteMark', '1')
            ->orderBy('SortNumber', 'desc')
            ->take(5)
            ->get();

        foreach ($bookHots as $k) {
            $k->FilePath1 = env('HOST') . $k->FilePath1;
        }
        return $bookHots;
    }


    /**
     * 获得读书会的成员的当日的读书改进计划数量
     * @param readPartyId 读书会ID
     * @pram date 指定的日期
     * */
    public function count_read_party_member_read_plan($readPartyId, $date = '')
    {
        $date = $date ? $date : current_date();
        $date = $date . "%";
        $sql = "SELECT COUNT(*) AS total FROM
                (SELECT d.SumUpID FROM read_party_member a
                LEFT JOIN memberinfo b ON  b.UserID = a.user_id
                LEFT JOIN booksumup  d ON  d.MemNumber = b.MemNumber
                WHERE a.read_party_id = $readPartyId
                AND   a.is_delete     = 0
                AND   d.AddDate like '{$date}'
                AND   b.DeleteMark  = 1
                GROUP BY d.MemNumber,BookID) AS  a";
        $info = DB::select($sql);
        return $info[0]->total;
    }


    /**
     * 获得会员该指定俱乐部下的学习币
     * @param string     memberNumber 会员编号
     * @param integer    readPartyId  读书会ID
     * @return integer
     * */
    public function get_member_money($memberNumber, $readPartyId)
    {
        $money = DB::table('membermoney')
            ->where('MemNumber', $memberNumber)
            ->where('ReaParID', $readPartyId)
            ->value('StudyMoney');
        if ($money) {
            return $money;
        }
        return 0;
    }

    /**
     * 重置学习币
     * @param string $memberNumber 会员编号
     * @param integer $readPartyId 读书会ID
     * */
    public function reset_member_money($memberNumber, $readPartyId)
    {
        DB::table('MemberMoney')
            ->where('MemNumber', $memberNumber)
            ->where('ReaParID', $readPartyId)
            ->update(['StudyMoney' => 0]);
    }


    /**
     * 获得所有已打赏出去的学习币
     * @param string memberNumber 会员编号
     * @param integer readPartyId  读书会ID
     * @return integer
     * */
    public function get_total_out_money($memberNumber, $readPartyId)
    {
        $moneyList  = DB::table('moneyrewardlog')
            ->where('MemNumber', $memberNumber)
            ->where('read_party_id', $readPartyId)
            ->pluck('MoReLoMoney');
        $totalMoney = 0;
        foreach ($moneyList as $money) {
            $totalMoney += $money;
        }
        return $totalMoney;
    }


    /**
     * 添加读书计划学习币
     * @param integer readPartyId 读书会ID
     * @param string   memberNumber 会员编号
     * @param integer studyMoney 学习币
     *
     * */
    public function add_read_plan_money($readPartyId, $memberNumber, $studyMoney)
    {
        mylogger(['id' => $readPartyId, 'mem' => $memberNumber, 'study' => $studyMoney]);
        $db          = DB::table('membermoney');
        $memberMoney = $db->where('ReaParID', $readPartyId)
            ->where('MemNumber', $memberNumber)
            ->first();
        if ($memberMoney) {
            $studyMoney += $memberMoney->StudyMoney;
            $db->where('StuMonID', $memberMoney->StuMonID)->update(['StudyMoney' => $studyMoney]);
        } else {

            $datetime = date_time();
            $data     = [
                "ReaParID"    => $readPartyId,
                'StudyMoney'  => $studyMoney,
                'MemNumber'   => $memberNumber,
                'ReleaseDate' => $datetime,
                'AddDate'     => $datetime
            ];
            $db->insert($data);
        }
    }


    /**
     * 添加读书计划打赏 详细记录每一条日志
     * @param array giftData 打赏的数据
     * @return boolean
     * */
    public function add_read_plan_money_gift($giftData)
    {

        /*检查是否已经有添加过*/
        $table       = DB::table('read_plan_money_gift_list');
        $commentId   = $giftData['comment_id'];
        $userId      = $giftData['user_id'];
        $readPartyid = $giftData['read_party_id'];
        $gift        = $table->select('money', 'id')
            ->where('comment_id', $commentId)
            ->where('read_party_id', $readPartyid)
            ->where('user_id', $userId)
            ->first();
        if ($gift) {
            $money = $gift->money + $giftData['money'];
            $table->where('id', $gift->id)->update(['money' => $money]);
            return true;
        }
        $info = $table->insert($giftData);
        if ($info) return true;
        else        return false;
    }


    /**
     * 获得读书计划打赏记录
     * @param integer commentId     读书计划ID
     * @param integer readPartyId  读书俱乐部ID
     * */
    public function get_read_plan_money_gift($commentId, $readPartyId)
    {
        $giftList = DB::table('read_plan_money_gift_list as a')
            ->leftJoin('memberinfo as b', 'b.UserID', '=', 'a.user_id')
            ->where('a.comment_id', $commentId)
            ->where('a.read_party_id', $readPartyId)
            ->select('b.YourName', 'b.UserID', 'a.money')
            ->get();

        return $giftList;
    }

    /**
     * 添加金币改变日志
     * @param array loginfo
     * @return integer
     * */
    public function add_money_change_log(array $logInfo)
    {

        $logInfo['AddDate'] = date_time();
        $logId              = DB::table('moneyrewardlog')->insertGetId($logInfo);
        return $logId;
    }


    /**
     * 添加读书计划评论信息
     *
     * */
    public function add_read_plan_comment()
    {

    }


    /**
     * 获得读书计划的评论信息
     * @param integer commentID 读书计划ID
     * @param integer readPartyId     读书会ID
     * */
    public function get_read_plan_comment($commentId, $readPartyId)
    {
        $comments = DB::table('commentreply as a')
            ->leftJoin('memberinfo as b', 'b.MemNumber', '=', 'a.MemNumber')
            ->select('a.CommContents', 'b.YourName')
            ->where('a.ReaParID', $readPartyId)
            ->where('a.CommID', $commentId)
            ->orderBy('RepID')
            ->get();
        foreach ($comments as $com) {
            $com->CommContents = emoji_text_decode($com->CommContents);
        }
        return $comments;
    }


    /*
    * 检查用户是否在职
    * */
    public function check_is_employee($userId, $readPartyId)
    {
        $count  = DB::table('read_party_member')
            ->where('user_id', $userId)
            ->where('read_party_id', $readPartyId)
            ->where('is_employee', 1)
            ->count();
        $result = $count > 0 ? true : false;
        return $result;
    }

    /**
     * 检查是否有打赏权限
     * */
    public function check_have_award_right($readPartyId, $userId)
    {
        $count  = DB::table('read_party_member')
            ->where('user_id', $userId)
            ->where('read_party_id', $readPartyId)
            ->where('is_employee', 1)
            ->where('reward_right', 1)
            ->count();
        $result = $count > 0 ? true : false;
        return $result;
    }


    public function get_read_party_member_info()
    {

    }


    /**
     * 考虑分页
     * */
    public function get_read_party_list($keywords = '')
    {
        $colums = [
            'a.ReaParID',
            'a.company_id',
            'a.ReaParType',
            'a.ReaParName',
            'a.AddDate',
            'b.UserName',
            'b.YourName',
            'b.NickName',
            'b.UserID',
            'd.company_name'
        ];
        $db     = DB::table('read_party as a')
            ->leftJoin('memberinfo as b', 'b.MemNumber', '=', 'a.MemNumber')
            ->leftJoin('company as d', 'd.company_id', 'a.company_id')
            ->select($colums)
            ->where('a.DeleteMark', '1');
        if ($keywords) {
            $db = $db->where(function ($query) use ($keywords) {
                $query->where('a.ReaParName', 'like', "%{$keywords}%")
                    ->orWhere('d.company_name', 'like', "%{$keywords}%");
            });

        }

        $readpartys = $db->orderBy('a.AddDate', 'desc')->paginate(20);
        return $readpartys;
    }


    /**
     *获取用户所在的地区
     * @param $userId 用户的ID
     * @return mixed 用户所在的地理位置
     */
    public function getUserCity($userId)
    {
        $city = DB::table('memberinfo as m')->select('r.region_name as city', 'rr.region_name as province', 'rrr.region_name as country')
            ->join('region as r', 'm.city', '=', 'r.region_id')
            ->leftJoin('region as rr', 'rr.region_id', '=', 'r.parent_id')
            ->leftJoin('region as rrr', 'rrr.region_id', '=', 'rr.parent_id')
            ->where('m.UserID', $userId)
            ->first();
        return $city;
    }

    /**
     * 部门添加部门的管理员
     * @param $departmentId 部门的ID
     * @param $user_id 用户的ID
     * @return mixed 返回受影响的行数
     */
    public function addCompanyDepartmentAdmin($departmentId, $user_id)
    {
        $status = DB::table('company_department')->where('department_id', $departmentId)
            ->update(['is_admin_user' => $user_id]);
        return $status;
    }

    /**
     * 判断用户是否是部门的管理员
     * @param $reaparId 读书会的ID
     * @return mixed
     */
    public function isTypeOfReadPart($reaparId)
    {
        $data = DB::table('read_party')->where('ReaParID', $reaparId)
            ->first(['ReaParType']);
        $type = $data->ReaParType;
        return $type;
    }

    /**
     * 读书会管理员权限的转让
     * @param $reaParId 读书的Id
     * @param $memNumber 要成为用户编号的管理员的编号
     * @return mixed 返回更新的状态
     */
    public function assignmentAdminModel($reaParId, $memNumber)
    {
        $status = DB::table('read_party')->where('ReaParID', $reaParId)->update(['MemNumber' => $memNumber]);
        return $status;
    }


    //下载excel读书会成员的信息
    public function getdown($id)
    {
//        DB::enableQueryLog();
        $data = DB::table('read_party_member as rpm')
            ->select('m.YourName', 'm.UserName', 'rpm.add_date', DB::raw('GROUP_CONCAT(cd.department_name,"【",cu.job,"】")'), 'rpm.reward_right')
            ->leftJoin('memberinfo as m', 'm.UserID', '=', 'rpm.user_id')
            ->leftJoin('company_user as cu', 'cu.user_id', '=', 'rpm.user_id')
            ->leftJoin('company_department as cd', 'cd.department_id', '=', 'cu.department_id')
            ->where(['m.DeleteMark' => 1, 'rpm.is_delete' => 0, 'rpm.read_party_id' => $id, 'cu.is_delete' => 0, 'cd.is_delete' => 0])
            ->groupBy('m.UserName')
            ->get();
//        dd(DB::getQueryLog());
        foreach ($data as $k => &$v) {
            $v->reward_right = $v->reward_right == 0 ? '否' : '是';
            $tmp[]           = collect($v)->toArray();
        }
        return $tmp;
    }
}